package com.qian.fmall.service.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qian.fmall.mapper.ProductMapper;
import com.qian.fmall.mapper.ProductSkuMapper;
import com.qian.fmall.pojo.Product;
import com.qian.fmall.pojo.ProductImg;
import com.qian.fmall.pojo.ProductSku;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SynchronousEs {

    private String index="product-index";
    private String type="product-type";

    @Resource
    private RestHighLevelClient client;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ObjectMapper om;

    @PostConstruct
    public void initDate()
    {
        try {
        List<Product> allProduct = productMapper.getAllProduct();
        BulkRequest req=new BulkRequest();
        for (Product product : allProduct) {
            //IndexRequest request = new IndexRequest(index,type,product.getProductId());
            Map<String,Object> valueMap = new HashMap();
            List<ProductImg> imgS = product.getImgs();
            for (ProductImg img : imgS) {
                if(img.getIsMain()==1)
                {
                    valueMap.put("productImg",img.getUrl());
                }
            }
            valueMap.put("productName",product.getProductName());
            valueMap.put("soldNum",product.getSoldNum());
            List<ProductSku> productSkuByProduct = productSkuMapper.getProductSkuByProductId(product.getProductId());
            if(!productSkuByProduct.isEmpty())
            {
                valueMap.put("price",productSkuByProduct.get(0).getOriginalPrice());
            }
            req.add(new IndexRequest(index,type,product.getProductId()).source(om.writeValueAsString(valueMap),XContentType.JSON));
            //request.source(om.writeValueAsString(valueMap),XContentType.JSON);
            //req.add(request);
        }
            BulkResponse bulk = client.bulk(req, RequestOptions.DEFAULT);
            System.out.println(bulk);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
